//
//  StatusPictureView.swift
//  Weibo10
//
//  Created by mac on 16/8/17.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

// 照片之间的距离
private let StatusPictureViewItemMargin: CGFloat = 8
// 可重用表示符号
private let StatusPictureCellId = "StatusPictureCellId"

class StatusPictureView: UICollectionView {

    // 微博视图模型
    var viewModle: StatusViewModel? {
        didSet {
            
            // 自动计算大小
            sizeToFit()
            
            reloadData()
        }
    }
    
    // 返回是collection View的大小
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
    }
    
    
    // MARK: - 构造函数
    init() {
        // 布局对象
        let layout = UICollectionViewFlowLayout()
        
        // 设置间距 Item默认间距 50 *50
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        // 调用父类的方法
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        // 设置背景颜色
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        bounces = false
        
        
        
        // 自定义视图的小框架可以自己做自己的数据源方法
        dataSource = self
        
        // 注册可重用的cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: - 数据源方法
extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModle?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = viewModle!.thumbnailUrls![indexPath.item]
        
        return cell
    }

}

// MARK: - 配图Cell
extension StatusPictureView {
    
    // 计算视图大小
    private func calcViewSize() -> CGSize {
        
        // 准备
        // 每行的照片数量
        let rowCount: CGFloat = 3
        
        // 最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        
        // item的宽度
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        // 设置 Item的ItemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        // 获取图片数量
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 获取图片数量
        let count = viewModle?.thumbnailUrls?.count ?? 0
        
        // 计算开始
        switch(count) {
        case 0: return CGSizeZero
        case 1: return CGSize(width: 150,height: 120)
        case 2: return CGSize(width: 2 * itemWidth + StatusPictureViewItemMargin, height: itemWidth)
        case 3: return CGSize(width: 3 * itemWidth + StatusPictureViewItemMargin * 2, height: itemWidth)
        case 4: return CGSize(width: 2 * itemWidth + StatusPictureViewItemMargin, height: 2 * itemWidth + StatusPictureViewItemMargin)
        case 5,6: return CGSize(width: 3 * itemWidth + StatusPictureViewItemMargin * 2, height: 2 * itemWidth + StatusPictureViewItemMargin)
        default: let row = CGFloat(8 / Int(rowCount) + 1)
            let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
            let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
            
            return CGSize(width: w, height: h)
        }
    }
}

// MARK: - 私有对象
private class StatusPictureViewCell: UICollectionViewCell {
    // 属性
    private lazy var iconView: UIImageView = UIImageView()
    
    
    // 配图cell
    var imageURL: NSURL? {
        
        didSet {
            iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,
                // SD 超时时长 15s，一旦超时会计入黑名单
                SDWebImageOptions.RefreshCached]
                // 如果URL不变，图像变
            )
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        // 添加控件
        contentView.addSubview(iconView)
        
        // 设置布局
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
}

